<template>
  <div :class="className" :style="{ height: height, width: width }" />
</template>

<script>
import echarts from 'echarts'
import { debounce } from '@/utils'

export default {
  props: {
    className: {
      type: String,
      default: 'chart',
    },
    width: {
      type: String,
      default: '100%',
    },
    height: {
      type: String,
      default: '500px',
    },
    series: {
      type: Array,
    },
  },
  data() {
    return {
      chart: null,
    }
  },
  mounted() {
    fetch('https://geo.datav.aliyun.com/areas_v3/bound/100000_full.json')
      .then(r => r.json())
      .then(r => {
        echarts.registerMap('map', r)
        this.initChart()
      })
    this.__resizeHandler = debounce(() => {
      if (this.chart) {
        this.chart.resize()
      }
    }, 100)
    window.addEventListener('resize', this.__resizeHandler)
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    window.removeEventListener('resize', this.__resizeHandler)
    this.chart.dispose()
    this.chart = null
  },
  methods: {
    initChart() {
      this.chart = echarts.init(this.$el)
      this.chart.setOption({
        geo: {
          map: 'map',
          left: 0,
          right: 0,
          top: 0,
          bottom: 0,
          itemStyle: {
            areaColor: 'rgba(255, 255, 255, 0.2)',
            borderColor: 'white',
          },
          emphasis: {
            label: {
              color: 'white',
            },
            itemStyle: {
              areaColor: 'rgba(255, 255, 255, 0.4)',
            },
          },
        },
        series: this.series,
      })
    },
  },
}
</script>
